package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.Flucard_IT.Home;
import com.Flucard_IT.SplashScreen;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import define.Class;
import define.Constants;

public class ConnectToServerAsync extends AsyncTask<String, Void, Boolean> {
	/**
	 * String section
	 */
	public static boolean IS_CONNECT_TO_CARD = false;

	/**
	 * View section
	 */

	/**
	 * The others section
	 */
	private Context context;

	public ConnectToServerAsync(Context context) {
		this.context = context;
	}

	@Override
	protected Boolean doInBackground(String... params) {
		return connectToServer();
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);

		IS_CONNECT_TO_CARD = result;
		if (SplashScreen.SSID != null & !SplashScreen.SSID.equals("")
				& IS_CONNECT_TO_CARD) {
			if (context.getClass().getSimpleName().equals(Class.SPLASH_SCREEN)) {
				/**
				 * If can get, transfer to new page
				 */
				((Activity) context).finish();

				/**
				 * If used correct wireless name, transfer to this page
				 */
				context.startActivity(new Intent(context, Home.class));
			}
		} else {
			/**
			 * Some times it can not run successfully,
			 * need add it to try-catch exception
			 */
			try {
				SplashScreen.mAdFailedConnection.show();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * Initial methods
	 */

	/**
	 * Basic methods
	 */

	private boolean connectToServer() {
		boolean relt = false;

		try {
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
			HttpConnectionParams.setSoTimeout(httpParams, 5000);
			HttpClient client = new DefaultHttpClient(httpParams);

			HttpGet request = new HttpGet("http://" + Constants.IP);
			HttpResponse response = client.execute(request);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line.indexOf(Constants.XML_INDEX) != -1) {
					relt = true;
					break;
				}
			}
			in.close();
			return relt;
		} catch (MalformedURLException e) {
			return relt;
		} catch (IOException e) {
			return relt;
		}
	}
}